package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.util.HttpUtils;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.swing.text.html.parser.Entity;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuth2Controller {

    @Value("${gitee.clientId}")
    String clientId;
    @Value("${gitee.redirectUri}")
    String redirectUri;
    @Value("${gitee.clientSecret}")
    String clientSecret;

    @Autowired
    MemberFeignService memberFeignService;


    @GetMapping("/oauth2.0/gitee/success")
    public String gitee(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
        //1.根据code换取accessToken
        //https://gitee.com/oauth/token?grant_type=authorization_code&code={code}&client_id={client_id}&redirect_uri={redirect_uri}&client_secret={client_secret}
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        map.put("client_id",clientId);
        map.put("redirect_uri",redirectUri);
        map.put("client_secret",clientSecret);
        map.put("grant_type","authorization_code");

        HttpResponse httpResponse = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post",new HashMap<>(),new HashMap<>(),map);
        System.out.println(httpResponse.getStatusLine().getStatusCode());
        //处理
        if (httpResponse.getStatusLine().getStatusCode()==200){
            //获取到了token
            String json = EntityUtils.toString(httpResponse.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
            //这里还要另外把gitee账户id封装进去作为用户标识
            Map<String,String> token = new HashMap<>();
            token.put("access_token",socialUser.getAccess_token());
            HttpResponse response = HttpUtils.doGet("https://gitee.com", "/api/v5/user", "get", new HashMap<>(), token);
            String j = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(j);
            String id = jsonObject.getString("id");
            //封装进socialUser
            socialUser.setUid(id);
            //知道当前是哪个社交用户
            //1.当前用户如果是第一次登录网站，自动注册进来(为当前社交用户生成一个会员信息账号，以后这个注册账号就对应这个会员)
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode()==0){
                MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登陆成功，用户:{}",data.toString());

                //1.第一次使用session：命令浏览器保存卡号。JSSESSIONID这个cookie
                //以后浏览器访问哪个网站都会带上这个网站的cookie
                //子域之间 gulimall.com auth.gulimall.com order.gulimall.com
                //发卡的时候 即使是子域系统发的卡也能让父域直接使用
                //TODO 1.默认发的令牌。session=dajkdja。作用域:当前域:(解决子域session共享问题)
                //TODO 2.使用json的序列化方式实现序列化对象数据到redis中
                httpSession.setAttribute("loginUser",data);
                //2.登录成功跳回首页
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

}
